package com.ydd.wrench.server.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cellplus.comm.util.ImpStringUtil;
import com.ydd.wrench.server.controller.CookieUtils;

/**
 * 权限控制拦截器
 * 
 * @author haoxw
 * @511/4
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	protected final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	protected static List<String> controllerUriFilter = Collections.synchronizedList(new ArrayList<String>());

	static {

		// controllerUriFilter.add("/back/queryAppActiveAnalyse/");
		// controllerUriFilter.add("/back/queryAppActiveAnalyseList/");
		// controllerUriFilter.add("/back/queryBusinessInterestUserInfo");
		// controllerUriFilter.add("/back/updateBusinessInterestUserStatus");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String requestURI = request.getRequestURI();
		if (StringUtils.contains(requestURI, ".")) {
			requestURI = StringUtils.substringBefore(requestURI, ".");
		}
		
		boolean bret = false;
		if ( bret ){
			return true;
		}

		if (controllerUriFilter.contains(requestURI)) {
			return true;
		}
		
		if (  ImpStringUtil.contains(requestURI, "userTypeFailed") ){
		  return true;
		}
		
		// 判断访问其他页必须登录，否则中断执行跳转到登录页
		if (!StringUtils.contains(requestURI, "login") && !StringUtils.contains(requestURI, "toLogin")) {
			String userId = CookieUtils.getInstance().getUserId(request);
		   int type = CookieUtils.getInstance().getUserType(request);
		    if ( ImpStringUtil.contains(requestURI, "design") ){
		      if ( type != 2){
		        response.sendRedirect(request.getContextPath() + "/ser/userTypeFailed");
		      }
		    }
		    else if ( ImpStringUtil.contains(requestURI, "run")){
		      if ( type != 1){
		        response.sendRedirect(request.getContextPath() + "/ser/userTypeFailed");
		      }
		    }
			
			if ( userId.equals("admin"))
			  return true;
			if ( !ImpStringUtil.isEmpty(userId)) {
				return true;
			} else {
				response.sendRedirect(request.getContextPath() + "/ser/toLogin");
				return false;
			}
		}
				
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//		if (modelAndView == null) {
//			modelAndView = new ModelAndView();
//		}
//		String baseUrl = "http://localhost:8080/";
//		modelAndView.addObject("jsPath", baseUrl + "/js");
//		modelAndView.addObject("cssPath", baseUrl + "/css");
//		modelAndView.addObject("imgPath", baseUrl + "/images");
//		modelAndView.addObject("context_path", request.getContextPath());// 应用路径
//		modelAndView.addObject("staticPath", baseUrl);
//		modelAndView.addObject("css_version", "1");
//		modelAndView.addObject("js_version", "1");
//		String cookieValue = CookieUtils.getInstance().getCookieValue(request);
//		// userId|deviceType|deviceId|token|lastLoginTime
//		if (StringUtils.isNotEmpty(cookieValue)) {
//			long userId = CookieUtils.getInstance().getUserId(request);
//			String deviceType = CookieUtils.getInstance().getUserDeviceType(request);
//			String deviceId = CookieUtils.getInstance().getUserDeviceId(request);
//			modelAndView.addObject("deviceType", deviceType);
//			modelAndView.addObject("deviceId", deviceId);
//			modelAndView.addObject("uid", userId);
//		}
//		logger.info("AuthInterceptor postHandle finish");
		super.postHandle(request, response, handler, modelAndView);
	}
}
